package xyz.hubery.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import xyz.hubery.domain.SysMenu;
import xyz.hubery.model.R;
import xyz.hubery.model.RolePrivilegesParam;
import xyz.hubery.service.SysMenuService;
import xyz.hubery.service.SysPrivilegeService;
import xyz.hubery.service.SysRolePrivilegeService;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "角色的权限管理")
@RestController
public class RolePrivilegeController {

    @Autowired
    private SysMenuService menuService;
    @Autowired
    private SysRolePrivilegeService rolePrivilegeService;


    @GetMapping("/roles_privileges")
    // @PreAuthorize("hasAuthority('')")
    @ApiImplicitParam(name = "roleId", value = "角色id")
    @ApiOperation(value = "查询角色的所有权限")
    public R<List<SysMenu>> queryMenuAndPrivileges(Long roleId) {
        // 1、根据父菜单id查询所有的子菜单
        List<SysMenu> menus = menuService.getChildMenusByParentId(null);
        // 过滤最顶级菜单
        List<SysMenu> menuList = new ArrayList<>();
        for (SysMenu menu : menus) {
            menuList.addAll(menu.getChilds());
        }
        // 2、查询最底层菜单的权限列表  查询权限时判断是否属于该角色
        menuService.querySubMenuPrivileges(menuList,roleId);
        return R.ok(menuList);
    }


    @PostMapping("/grant_privileges")
    @ApiOperation(value = "授予角色权限")
    @ApiImplicitParam(name = "rolePrivilegesParam",value = "RolePrivilegesParam的json数据")
    public R<Boolean> addRolePrivileges(@RequestBody RolePrivilegesParam rolePrivilegesParam) {
       boolean b = rolePrivilegeService.addRolePrivileges(rolePrivilegesParam);
        if(b){
            return R.ok();
        }
        return R.fail();
    }


}
